package api

import (
	"My_Blog02/model"
	"My_Blog02/utils/errmsg"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 添加用户
func AddUser(c *gin.Context) {
	var user model.User
	err := c.ShouldBindJSON(&user)
	if err != nil {
		code := errmsg.ERROR
		c.JSON(200, gin.H{
			"code":    code,
			"message": errmsg.GetMsg(code),
			"data":    "",
		})
	}
	data, code := model.AddUser2(user)
	c.JSON(200, gin.H{
		"code":    code,
		"message": errmsg.GetMsg(code),
		"data":    data,
	})

}

// 删除用户
func DeleteUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		code := errmsg.ERROR
		c.JSON(200, gin.H{
			"code":    code,
			"message": errmsg.GetMsg(code),
			"data":    "",
		})
	}
	data, code := model.DeleteUser2(id)
	c.JSON(200, gin.H{
		"code":    code,
		"message": errmsg.GetMsg(code),
		"data":    data,
	})

}

// 修改用户
func ModifyUser(c *gin.Context) {
	var user model.User
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		code := errmsg.ERROR
		c.JSON(200, gin.H{
			"code":    code,
			"message": errmsg.GetMsg(code),
			"data":    "",
		})
	}
	err = c.ShouldBindJSON(&user)
	if err != nil {
		code := errmsg.ERROR
		c.JSON(200, gin.H{
			"code":    code,
			"message": errmsg.GetMsg(code),
			"data":    "",
		})
	}
	data, code := model.ModifyUser2(id, user)
	c.JSON(200, gin.H{
		"code":    code,
		"message": errmsg.GetMsg(code),
		"data":    data,
	})
}

// 查询用户
func GetUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		code := errmsg.ERROR
		c.JSON(200, gin.H{
			"code":    code,
			"message": errmsg.GetMsg(code),
			"data":    "",
		})
	}
	data, code := model.GetUser2(id)
	c.JSON(200, gin.H{
		"code":    code,
		"message": errmsg.GetMsg(code),
		"data":    data,
	})
}
